package com.geeklan.smart.ui.device;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.base.utils.ActivityUtil;
import com.geeklan.base.utils.MLog;
import com.geeklan.smart.MLMApplication;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.Device;
import com.geeklan.smart.data.model.DeviceStatusResponse;
import com.geeklan.smart.data.model.DeviceVersion;
import com.geeklan.smart.data.repository.device.DeviceRepository;
import com.geeklan.smart.databinding.ActivityDeviceSettingsBinding;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.dialog.ClearFoodAlertDialog;
import com.geeklan.smart.ui.dialog.DelDeviceAlertDialog;
import com.geeklan.smart.ui.dialog.DeviceUpdateAlertDialog;
import com.geeklan.smart.ui.dialog.EditTextAlertDialog;
import com.geeklan.smart.ui.dialog.ResetDeviceAlertDialog;
import com.geeklan.smart.ui.dialog.SmartFoodBottomSheetDialog;
import com.geeklan.smart.ui.dialog.UploadDeviceLogAlertDialog;
import com.geeklan.smart.ui.feed.FeedPlanActivity;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModel;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModelFactory;
import com.geeklan.smart.utils.CopyUtils;
import com.geeklan.smart.utils.VersionComparator;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class DeviceSettingsActivity extends BaseActivity<ActivityDeviceSettingsBinding> implements View.OnClickListener {
    private DeviceViewModel deviceViewModel;
    private String deviceId;
    private String deviceName;
    private DeviceStatusResponse.DataDTO device;
    private int smartFoodBowl;
    private DeviceVersion deviceVersion;
    private String curDeviceVersion;
    @Override
    protected ActivityDeviceSettingsBinding initBinding() {
        return ActivityDeviceSettingsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        deviceId = getIntent().getStringExtra("deviceId");
        deviceViewModel = new ViewModelProvider(this, new DeviceViewModelFactory(new DeviceRepository())).get(DeviceViewModel.class);

        deleteUserBindDevice();
        renameDevice();
        clearBowlDevice();
        sendGetLog();
        intelligentFoodBowlDevice();
        onlineStatusLiveData();
        onlineStatusUpdateLiveData();
        getDeviceVersion();
    }

    private void deleteUserBindDevice(){
        deviceViewModel.getDeleteUserBindDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            MLMApplication.getUmeng().deleteTags(deviceId);
            ActivityUtil.getInstance().finishActivity(DeviceSettingsActivity.class);
            ActivityUtil.getInstance().finishActivity(DeviceInfoActivity.class);
            EventBus.getDefault().post(new Device());
        });

        deviceViewModel.getDeleteUserBindDeviceErrorLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }
    private void intelligentFoodBowlDevice(){
        deviceViewModel.getIntelligentFoodBowlDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            Toast.makeText(this, R.string.update_success, Toast.LENGTH_SHORT).show();
            deviceViewModel.getDeviceById(deviceId);
        });
        deviceViewModel.getIntelligentFoodBowlErrorDeviceLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }
    private void sendGetLog(){
        deviceViewModel.getSendGetLogLiveData().observe(this, apiResponse -> {
            dismiss();
            Toast.makeText(this, R.string.update_success, Toast.LENGTH_SHORT).show();
        });

        deviceViewModel.getSendGetLogErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, R.string.request_fail, Toast.LENGTH_SHORT).show();
        });
    }
    private void clearBowlDevice(){
        deviceViewModel.getClearBowlDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            Toast.makeText(this, R.string.update_success, Toast.LENGTH_SHORT).show();
        });

        deviceViewModel.getClearBowlErrorLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }
    private void renameDevice(){
        deviceViewModel.getRenameDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            Toast.makeText(this, R.string.update_success, Toast.LENGTH_SHORT).show();
            deviceViewModel.getDeviceById(deviceId);
        });

        deviceViewModel.getRenameErrorLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }

    private void getDeviceVersion(){
        deviceViewModel.getDeviceVersionDeviceLiveData().observe(this, apiResponse -> {
            if(apiResponse != null && apiResponse.getData() != null && !apiResponse.getData().isEmpty()) {
                List<DeviceVersion> deviceVersions = apiResponse.getData();
                deviceVersion = deviceVersions.get(0);
                if(VersionComparator.compareVersions(deviceVersion.getVersion(),curDeviceVersion) == 1){
                    mBinding.ivNewVersion.setVisibility(View.VISIBLE);
                    mBinding.llOtaUpdate.setEnabled(true);
                }else {
                    mBinding.ivNewVersion.setVisibility(View.GONE);
                    mBinding.llOtaUpdate.setEnabled(false);
                }
            }else {
                mBinding.llOtaUpdate.setEnabled(false);
            }
        });
        deviceViewModel.getDeviceVersionDeviceErrorLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });


        deviceViewModel.getFirmwareUpgradeDeviceLiveData().observe(this, apiResponse -> {
            handler.sendEmptyMessage(0);
            Toast.makeText(this, getString(R.string.device_updating), Toast.LENGTH_SHORT).show();
        });
        deviceViewModel.getFirmwareUpgradeDeviceErrorLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }

    private void onlineStatusUpdateLiveData(){
        deviceViewModel.getDeviceStatusUpdateLiveData().observe(this, apiResponse -> {
            try {
                List<DeviceStatusResponse.DataDTO> data = apiResponse.getData();
                if(data != null && data.get(0) != null){
                    device = data.get(0);
                    smartFoodBowl = device.getSmartFoodBowl();
                    if(smartFoodBowl == 0){
                        mBinding.tvSmartFoodStatus.setText(getString(R.string.close));
                    } else if(smartFoodBowl == 1){
                        mBinding.tvSmartFoodStatus.setText(getString(R.string.open));
                    }
                    deviceName = device.getDeviceName();
                    mBinding.tvDeviceName.setText(deviceName);
                    mBinding.tvDeviceCode.setText(device.getDeviceId());
                    if(device.getVersion() != null && !device.getVersion().equals("")) {
                        mBinding.tvDeviceVersion.setText("v" + device.getVersion());
                    }

                    String context = getString(R.string.settings_smart_food_content);
                    String context1 = String.format(context,device.getSmartFootBowlWeight());
                    mBinding.textView2.setText(context1);

                    curDeviceVersion = device.getVersion();

                    if(VersionComparator.compareVersions(deviceVersion.getVersion(),curDeviceVersion) == 1){
                        mBinding.ivNewVersion.setVisibility(View.VISIBLE);
                        mBinding.llOtaUpdate.setEnabled(true);
                        handler.sendEmptyMessageDelayed(0,5000);
                    }else {
                        mBinding.ivNewVersion.setVisibility(View.GONE);
                        mBinding.llOtaUpdate.setEnabled(false);
                        dismiss();
                        Toast.makeText(this, getString(R.string.device_update_success), Toast.LENGTH_SHORT).show();
                    }
                }else {
                    dismiss();
                    Toast.makeText(this, getString(R.string.device_update_success), Toast.LENGTH_SHORT).show();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        deviceViewModel.getDeviceStatusUpdateErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, getString(R.string.device_update_fail), Toast.LENGTH_SHORT).show();
        });
    }

    private void onlineStatusLiveData(){
        deviceViewModel.getDeviceStatusLiveData().observe(this, apiResponse -> {
            try {
                List<DeviceStatusResponse.DataDTO> data = apiResponse.getData();
                if(data != null && data.get(0) != null){
                    device = data.get(0);
                    smartFoodBowl = device.getSmartFoodBowl();
                    if(smartFoodBowl == 0){
                        mBinding.tvSmartFoodStatus.setText(getString(R.string.close));
                    } else if(smartFoodBowl == 1){
                        mBinding.tvSmartFoodStatus.setText(getString(R.string.open));
                    }
                    deviceName = device.getDeviceName();
                    mBinding.tvDeviceName.setText(deviceName);
                    mBinding.tvDeviceCode.setText(device.getDeviceId());
                    if(device.getVersion() != null && !device.getVersion().equals("")) {
                        mBinding.tvDeviceVersion.setText("v" + device.getVersion());
                    }

                    String context = getString(R.string.settings_smart_food_content);
                    String context1 = String.format(context,device.getSmartFootBowlWeight());
                    mBinding.textView2.setText(context1);

                    curDeviceVersion = device.getVersion();
                    deviceViewModel.getDeviceVersion();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            dismiss();
        });


        deviceViewModel.getDeviceStatusErrorLiveData().observe(this, s -> {
            dismiss();
        });
        deviceViewModel.getDeviceById(deviceId);
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(System.currentTimeMillis() - deviceUpdateStartTime > 300 * 1000){
                dismiss();
                Toast.makeText(DeviceSettingsActivity.this, getString(R.string.device_update_fail), Toast.LENGTH_SHORT).show();
            }else {
                deviceViewModel.getDeviceByIdUpdate(deviceId);
            }
            return false;
        }
    });

    @Override
    protected void initView() {
        mBinding.clFeedPlan.setOnClickListener(this);
        mBinding.ivBack.setOnClickListener(this);
        mBinding.tvDelDevice.setOnClickListener(this);
        mBinding.llDeviceName.setOnClickListener(this);
        mBinding.llFoodClear.setOnClickListener(this);
        mBinding.llResetDevice.setOnClickListener(this);
        mBinding.ivCopy.setOnClickListener(this);
        mBinding.llOtaUpdate.setOnClickListener(this);
        mBinding.llUploadDeviceLog.setOnClickListener(this);
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context, String deviceId) {
        Intent intent = new Intent(context, DeviceSettingsActivity.class);
        intent.putExtra("deviceId", deviceId);
        context.startActivity(intent);
    }
    private long deviceUpdateStartTime = 0;
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == mBinding.clFeedPlan.getId()) {
            SmartFoodBottomSheetDialog alertDialog = new SmartFoodBottomSheetDialog(this,getString(R.string.pet_smart_feed_bowl),smartFoodBowl);
            alertDialog.setFoodGrams(device.getSmartFootBowlWeight());
            alertDialog.setOnPositiveButtonClickListener(v1 -> {
                alertDialog.dismiss();

                String context = getString(R.string.settings_smart_food_content);
                String context1 = String.format(context,alertDialog.getFoodGrams());
                mBinding.textView2.setText(context1);
                deviceViewModel.intelligentFoodBowl(deviceId,alertDialog.getSmartFoodBowl(),alertDialog.getFoodGrams());
            });
            alertDialog.show();
        } else if (id == mBinding.ivBack.getId()) {
            finish();
        } else if (id == mBinding.tvDelDevice.getId()) {
            DelDeviceAlertDialog alertDialog = new DelDeviceAlertDialog(this,getString(R.string.dialog_tips));
            alertDialog.setShowRelativeLayoutButton(v1 -> {
                loading();
                deviceViewModel.deleteUserBindDevice(deviceId);
            },v1 -> alertDialog.dismiss());
            alertDialog.show();
        } else if (id == mBinding.llDeviceName.getId()) {
            EditTextAlertDialog alertDialog = new EditTextAlertDialog(this, getString(R.string.device_rename));
            alertDialog.setShowRelativeLayoutButton(v1 -> {
                String name = alertDialog.getContentText();
                if(TextUtils.isEmpty(name)) {
                    Toast.makeText(this,"请输入设备名称",Toast.LENGTH_SHORT).show();
                    return;
                }

                if(name.length() > 20) {
                    Toast.makeText(this,"设备名称不能超过20字",Toast.LENGTH_SHORT).show();
                    return;
                }
                alertDialog.dismiss();
                loading();
                deviceViewModel.updateDeviceInfo(deviceId,name);
            },v1 -> alertDialog.dismiss());
            alertDialog.setHint("");
            alertDialog.show();
        } else if (id == mBinding.llFoodClear.getId()) {
            ClearFoodAlertDialog alertDialog = new ClearFoodAlertDialog(this,getString(R.string.dialog_tips));
            alertDialog.setShowRelativeLayoutButton(v1 -> {
                alertDialog.dismiss();
                loading();
                deviceViewModel.clearBowl(deviceId);
            },v1 -> alertDialog.dismiss());
            alertDialog.show();
        } else if (id == mBinding.llResetDevice.getId()) {
            ResetDeviceAlertDialog alertDialog = new ResetDeviceAlertDialog(this,getString(R.string.dialog_tips));
            alertDialog.setShowRelativeLayoutButton(v1 -> {
                alertDialog.dismiss();
                loading();
                deviceViewModel.resetDevice(deviceId);
            },v1 -> alertDialog.dismiss());
            alertDialog.show();
        } else if (id == mBinding.ivCopy.getId()) {
            CopyUtils.copyToClipboard(this,device.getDeviceId());
        } else if (id == mBinding.llOtaUpdate.getId()) {
            if(device.getOnlineStatus() == 1) {
                DeviceUpdateAlertDialog alertDialog = new DeviceUpdateAlertDialog(this, getString(R.string.ota_update));
                alertDialog.setPositiveButtonText(getString(R.string.ok));
                alertDialog.setVersion(deviceVersion.getVersion(),Long.parseLong(deviceVersion.getFileSize()));
                alertDialog.setOnPositiveButtonClickListener(v1 -> {
                    alertDialog.dismiss();
                    loading(R.string.device_updating);
                    deviceUpdateStartTime = System.currentTimeMillis();
                    deviceViewModel.firmwareUpgrade(deviceVersion.getId(),deviceId);
                });
                alertDialog.show();
            }else {
                Toast.makeText(this,getString(R.string.device_offline),Toast.LENGTH_SHORT).show();
            }
        } else if (id == mBinding.llUploadDeviceLog.getId()) {
            if(device.getOnlineStatus() == 1) {
                UploadDeviceLogAlertDialog alertDialog = new UploadDeviceLogAlertDialog(this,getString(R.string.dialog_tips));
                alertDialog.setShowRelativeLayoutButton(v1 -> {
                    alertDialog.dismiss();
                    loading();
                    deviceViewModel.sendGetLogCommand(deviceId);
                },v1 -> alertDialog.dismiss());
                alertDialog.show();
            }else {
                Toast.makeText(this,getString(R.string.device_offline),Toast.LENGTH_SHORT).show();
            }
        }
    }
}